import { ServerResponse } from "./serverResponse";
import { config, Config } from '../config/index'

export default class Request {
	//配置信息
	private static conf: Config = config;

	private static excludes = ["/login", "/getPhone"];

	// 判断是否为登陆接口
	private static excludeFilter(url: string): boolean {
		for (let i = 0; i < this.excludes.length; i++) {
			if (url.indexOf(this.excludes[i]) > 0) {
				return true
			}
		}

		return false
	}

	// get请求
	public static get<R>(url: string, params?: any, contentType: string = "application/json"): Promise<ServerResponse<R>> {
		return new Promise((resolve: any, reject: any) => {
			let requestOptions: any = { "header": { "content-type": contentType } }

			if (!this.excludeFilter(url)) {
				let t = wx.getStorageSync('t')
				t = t || ''
				requestOptions.header["Authorization"] = `Bearer ${t}`
			}

			wx.request({
				method: 'GET',
				url: this.conf.baseUrl + url,
				data: params,
				...requestOptions,
				success: (res: any) => {
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}

	// post请求
	public static post<R>(url: string, data?: any, contentType: string = "application/json"): Promise<ServerResponse<R>> {
		return new Promise((resolve: any, reject: any) => {
			let requestOptions: any = { "header": { "content-type": contentType } }

			if (!this.excludeFilter(url)) {
				let t = wx.getStorageSync('t')
				t = t || ''
				requestOptions.header["Authorization"] = `Bearer ${t}`
			}

			wx.request({
				method: 'POST',
				url: this.conf.baseUrl + url,
				data: data,
				...requestOptions,
				success: (res: any) => {
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}
}